package com.guit.hrms.interceptors;

import com.guit.hrms.po.api.Api;
import com.guit.hrms.service.ApiService;
import com.guit.hrms.service.TokenService;
import com.guit.hrms.utils.JwtUtil;
import com.guit.hrms.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.Map;


@Component
public class AllRequestInterceptor implements HandlerInterceptor {
    @Autowired
    private ApiService apiService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String,Object> map = ThreadLocalUtil.get();
        String employeeId = (String) map.get("employeeId");

        String path = request.getRequestURI();
        String method = request.getMethod();

        System.out.println("All请求路径: " + path);  // 直接用 System.out 打印，确保能看到
        System.out.println("All请求方式"+method);
        String completeApi = method+"_"+path;
        System.out.println("completeApi = " + completeApi);
        Api api = apiService.verifyApi(employeeId,completeApi);


        if (api != null) {
            return true;
        }
        response.setStatus(403);
        return false;
    }

    @Override //请求（接口）结束后执行
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThreadLocal中的数据
        ThreadLocalUtil.remove();
    }
}
